<?php

namespace app\shop\controller;

use app\shop\model\ShopStoreGoodsCate;
use app\shop\model\ShopStoreGoodsSpec;
use app\shop\model\ShopStoreGoodsSpecs;
use app\shop\model\ShopStoreGoodsStock;
use app\common\service\Status;
use app\shop\model\ShopStoreGoods;
use buildView\Actions;
use buildView\Button;
use app\common\tools\Excel;
use buildView\Filter;
use buildView\Form;
use buildView\Grid;
use library\Controller;
use library\tools\Data;
use think\Db;
use think\db\Query;

/**
 * 店铺商品信息管理
 * Class StoreGoods
 * @package app\admin\controller
 */
class StoreGoods extends Controller
{
    /**
     * 商品列表
     * @auth true
     * @mentu true
     * @return string
     */
    public function index()
    {
        $grid = new Grid(new ShopStoreGoods());
        $filter_stock_warning = $this->request->get('stock_warning');
        $stock_warning = sysconf('stock_warning');
        $grid->model()->withSum('specs', 'stock')->withSum(['specs' => function ($q) {
            return 'sale_num';
        }], 'sale')->when($filter_stock_warning, function (Query $q) use ($stock_warning) {
            $sql = ShopStoreGoodsSpec::whereRaw('shop_store_goods.id=shop_store_goods_spec.gid')->where('is_deleted', 0)->whereRaw('stock < ' . $stock_warning)->buildSql();
            $q->whereExists($sql);
        });
        $button = new Button('导入');
        $button->href(url('uploadXls').'?back=1', 'modal');
        $grid->addTools($button);

        $grid->logo('商品图片')->excelClose()->width(150)->image(5,80,80);
        $grid->column('info', '商品信息')->display(function ($val, $data) {
            $html = "商品编号：{$data['id']}<br>所属分类：{$data['cate']['title']}<br>商品名称：{$data['title']}";
            return $html;
        })->width(200)->setExcelData(function($val,$data){
            $html = "商品编号：{$data['id']}  所属分类：{$data['cate']['title']}  商品名称：{$data['title']}";
            return $html;
        })->align('left');
        $grid->column('specs', '商品规格')->display(function ($specs, $data) use ($stock_warning) {
                $html = '<div class="layui-row" style="line-height:23px">
                        <div class="layui-col-xs6 text-left layui-elip font-s10">--</div>
                    </div>';
                if ($specs->isEmpty()) {
                    return $html;
                } else {
                    $html = '<div style="overflow:auto;padding:5px 0">';
                }
                foreach ($specs as $spec) {
                    $stock = $spec['stock']-$spec['sale'];
                    if($stock <= $stock_warning){
                        $stock = '<span class="color-red">'.$stock.'</span>';
                    }

                    $html .= ' <div class="layui-row" style="line-height:23px">
                        <div class="layui-col-xs3 text-left layui-elip font-s10">' . str_replace(['::', ';;'], [':', ';'], $spec['spec_name']) . '</div>
                        <div class="layui-col-xs3 text-center layui-elip color-blue font-s10">'  .'售价： ' . $spec['price'] . '</div>
                        <div class="layui-col-xs3 text-center layui-elip color-blue font-s10">' .'库存： '. $stock . '</div>
                    </div>';
                }
                $html .= '</div>';
                return $html;
            })->minWidth(550)->setExcelData(function($specs,$data) use ($stock_warning) {
                $html = '';
                foreach ($specs as $spec) {
                    $stock = $spec['stock']-$spec['sale'];
                    if($stock <= $stock_warning){
                        $stock = $stock;
                    }
                    $spec_name = str_replace(['::', ';;'], [':', ';'], $spec['spec_name']);
                    $html .= "规格名称：{$spec_name} 售价：{$spec['price']} 库存：{$spec['stock']} ";
                }
                return $html;
            })->align('center');
        $grid->column('sale_num', '库存统计')->display(function ($val, $data) use ($stock_warning) {
            $stock = $data['specs_sum'] ? $data['specs_sum']:0;
            return $stock;
        })->width(150)->setExcelData(function($val,$data) use ($stock_warning) {
            $stock = $data['specs_sum'] ? $data['specs_sum']:0;
            return $stock;
        })->align('left')->sort();
        $grid->column('price', '价格')->display(function ($val, $data) {
            return '￥' . $data['price'];
        })->width(150)->align('left');
        $grid->column('status', '商品状态')->width(150)->setExcelData(function($val,$data) {
            if ($val){
                $html = '上架';
            }else{
                $html = '下架';
            }
            return $html;
        })->align('left')->switchs([
            'on' => ['text' => '上架', 'value' => 1],
            'off' => ['text' => '下架', 'value' => 0],
        ]);
        $grid->actions(function (Actions $action, $data) {
            $action->hideDetail();
            $button = new Button('出库', 'warm', 'sm', 'layui-icon-down');
            $button->href(url('stock') . "?goods_id={$data['id']}&title={$data['title']}&type=2", 'modal');
            $html = $button->render() . '<br>';
            $action->prepend($html);
            $button = new Button('入库', 'normal', 'sm', 'layui-icon-up');
            $button->href(url('stock') . "?goods_id={$data['id']}&title={$data['title']}&type=1", 'modal');
            $html = $button->render();
            $action->prepend($html);
            $action->width(200);
        });
        $grid->filter(function (Filter $filter) {
            $filter->like('title', '商品名称');
            $cates = ShopStoreGoodsCate::field('id,title as text,pid')->where('pid', 0)->with(['son' => function ($q) {
                $q->field('id,title as text,pid');
            }])->select();
            $filter->eq('cate_id','商品分类')->selectGroup($cates);
            $filter->eq('status', '商品状态')->select(Status::SHOPSTATUS());
            $filter->eq('stock_warning','库存状态')->select([
                'stock'=>'库存预警',
            ]);
        });
        return $grid->view();
    }


    /**
     * 上传导入文件
     * @auth true
     * @menu true
     */
    public function uploadXls()
    {
        $form = new Form(new ShopStoreGoods);
        //文件上传 只允许jpg
        $form->file('file','上传文件')->uploadType('xls,xlsx')->required();
        $form->saving(function($post){
            //导入字段名
            $field = [
                'title',
                'cate_id',
                'goods',
                'price',
                'mini_title'
            ];
            $table = 'shop_store_goods';
            $info = Excel::inport($post['file'],$table,$field);
            if ($info){
                foreach($info as $key => $value){
                    foreach ($value as $e => $v){
                        if (!$v){
                            unset($info[$key]);
                        }
                    }
                    if ($value['goods']){
                        $spec_info = explode(';',$value['goods']);
                        $spec_arr = [];
                        if ($spec_info){
                            foreach ($spec_info as $ke => $val){
                                $spec_item = explode(' ',$val);
                                $spec_arr[] = $spec_item;
                            }
                        }
                    }
                }
                foreach ($info as $k => $v){
                    $cate_id = Db::name('shop_store_goods_cate')->where('title',$v['cate_id'])->value('id');
                    $cate_id?$info[$k]['cate_id'] = $cate_id:$this->error("未找到{$v['cate_id']}分类");
                    $info[$k]['spec'] = $spec_arr;
                }
            };
            if ($info){
                foreach ($info as $kk => $vv){
                    $goods_data = [
                        'title' => $vv['title'],
                        'cate_id' => $vv['cate_id'],
                        'price' => $vv['price'],
                        'mini_title' => $vv['mini_title'],
                    ];
                    $good_id = Db::name('shop_store_goods')->insertGetId($goods_data);
                    if ($vv['spec']){
                        foreach ($vv['spec'] as $sk => $c){
                            $specArr[] = [
                                'gid' => $good_id,
                                'goods_title' => $vv['title'],
                                'spec_group' => explode(':', $c[0])[1],
                                'spec_type' => explode(':', $c[0])[0],
                                'spec' => explode(':', $c[0])[1],
    //                        'degrees' => explode(':', $spec[1])[1],
                                'spec_name' => $c[0],
    //                        'price_market' => $post['spec']['price_market'][$key],
                                'price' => explode(':', $c[1])[1],
    //                        'thumb' => $post['spec']['thumb'][$key],
                                //  'status' => $post['spec']['status'][$key],
                                'is_deleted' => 0
                            ];
                        }
                    }
                }
            }
            (new ShopStoreGoodsSpec)->saveAll($specArr);
        });
        return $form->view();
    }

    /**
     * 添加/编辑
     * @auth true
     * @mentu true
     * @return string
     */
    public function form()
    {
        $form = new Form(new ShopStoreGoods());
        $form->setThemePane();
        $cates = ShopStoreGoodsCate::field('id,title')->where('pid', 0)->column('title','id');
        $form->text('title', '商品名称')->required();
        $form->select('cate_id', '商品分类')->options($cates)->default(1)->layui('inline')->md(4)->required();
        $form->number('price', '单价')->layui('inline')->md(4)->required();
        $form->image('logo', 'LOGO')->layui('block text-center')->md(1)->help('建议图片尺寸200 * 80')->required();
        $form->image('image', '轮播图')->multiple()->md(10)->help('建议图片尺寸200 * 80');
        $form->text('mini_title', '备注');
        $data = $form->getModelData();
        $specs = ShopStoreGoodsSpecs::where('status', 1)->select();
        $form->spec('specs', '商品规格')->spec_id($data['spec_id'])->specs($specs);
        $form->ckeditor('content', '说明');
        $form->saved(function ($post, $data) {
            $specArr = [];
            $goodSpec = [];
            $good_id = $data['id'];

            foreach ($post['spec']['id'] as $key => $spec_id) {
                // 创建搜索字段
                $spec_group = explode(',', $post['spec']['spec_name'][$key]);
                $select_str = '';
                $spec_type_name = '';
                foreach ($spec_group as $k => $val) {
                    $spec_group_arr = explode(':', $val);
                    if ($k == 0) {
                        $select_str .= $spec_group_arr[1];
                        $spec_type_name = $spec_group_arr[0];
                    } else {
                        $select_str .= '-' . $spec_group_arr[1];
                        $spec_type_name .= '-' . $spec_group_arr[0];
                    }
                }
                $spec = explode(',', $post['spec']['spec_name'][$key]);
                if ($post['spec']['price'][$key] <= 0) {
                    $this->error('请输入正确的销售价格！');
                }
                if ($post['spec']['price_market'][$key] <= 0) {
                    $this->error('请输入正确的市场价格！');
                }
                ShopStoreGoodsSpec::where('gid', $good_id)->setField('is_deleted', 1);
                if (empty($spec_id)) {
                    $specArr[] = [
                        'gid' => $good_id,
                        'goods_title' => $post['title'],
                        'spec_group' => $select_str,
                        'spec_type' => $spec_type_name,
                        'spec' => explode(':', $spec[0])[1],
                        'degrees' => explode(':', $spec[1])[1],
                        'spec_name' => $post['spec']['spec_name'][$key],
                        'price_market' => $post['spec']['price_market'][$key],
                        'price' => $post['spec']['price'][$key],
                        'thumb' => $post['spec']['thumb'][$key],
                        //  'status' => $post['spec']['status'][$key],
                        'is_deleted' => 0
                    ];
                } else {
                    $specArr[] = [
                        'id' => $spec_id,
                        'goods_title' => $post['title'],
                        'gid' => $good_id,
                        'spec_group' => $select_str,
                        'spec_type' => $spec_type_name,
                        'spec' => explode(':', $spec[0])[1],
                        'degrees' => explode(':', $spec[1])[1],
                        'spec_name' => $post['spec']['spec_name'][$key],
                        'price_market' => $post['spec']['price_market'][$key],
                        'price' => $post['spec']['price'][$key],
                        'thumb' => $post['spec']['thumb'][$key],
                        //   'status' => $post['spec']['status'][$key],
                        'is_deleted' => 0
                    ];
                }
                $goodSpec[] = $post['spec']['spec_name'][$key];
            }
            (new ShopStoreGoodsSpec)->saveAll($specArr);
            $spec = json_encode($goodSpec, JSON_UNESCAPED_UNICODE);
            ShopStoreGoods::where('id', $good_id)->setField('spec', $spec);
            return $post;
        });
        return $form->view();
    }

    /**
     * 商品出入库
     * @auth true
     * @mentu true
     * @return string
     */
    public function stock()
    {
        $goods_id = $this->request->get('goods_id');
        $title = $this->request->get('title');
        $type = $this->request->get('type');
        $form = new Form(new ShopStoreGoodsStock());
        $form->setTitle('商品出库');
        $form->hidden('goods_id', '商品id')->default($goods_id);
        $form->hidden('type', '出入库')->default($type);
        $form->text('title', '商品名称')->default($title)->readonly();
        $spec = ShopStoreGoodsSpec::where('gid', $goods_id)->where('is_deleted', 0)->select();
        $form->stock('spec', '规格详情')->type($type)->spec($spec);
        $form->textarea('desc', '描述');
        $form->saving(function ($post) use ($type) {
            $spec = [];
            $stockArr = [];
            $stock_bool = false;
            foreach ($post['spec_id'] as $key => $spec_id) {
                if ($post['goods_number'][$key] > 0) {
                    $stock_bool = true;
                    if($type == 1){
                        $spec[] = [
                            'id' => $spec_id,
                            'stock' =>  Db::raw("stock+{$post['goods_number'][$key]}")
                        ];
                    }else{
                        $spec[] = [
                            'id' => $spec_id,
                            'stock' => Db::raw("stock-{$post['goods_number'][$key]}")
                        ];
                    }
                    $stockArr[] = [
                        'spec_name' => $post['spec_name'][$key],
                        'num' => $post['goods_number'][$key]
                    ];
                }
            }
            if(!$stock_bool){
                $this->error('请填写正确数量');
            }
            (new ShopStoreGoodsSpec)->saveAll($spec);
            $post['goods_spec'] = json_encode($stockArr,JSON_UNESCAPED_UNICODE);
            return $post;
        });
        if($type == 1){
            $form->setSubmitText('确认入库');
        }else{
            $form->setSubmitText('确认出库');
        }
        return $form->view();
    }
}
